package middle

import (
	"gim-server/config"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/utils"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func AppAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		cfg := config.GetCfg()
		tokenStr := ctx.Request.Header.Get(consts.Token)
		tokenInfo, err := utils.ParseToken(cfg.SignKey, tokenStr)
		if err != nil {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiTokenErr,
				Err:  err,
				Msg:  "无效TOKEN",
			})
			ctx.Abort()
			return
		}
		claims := tokenInfo.Claims.(jwt.MapClaims)
		if claims[consts.AppID] != ctx.Request.Header.Get(consts.AppID) {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiTokenErr,
				Err:  err,
				Msg:  "APP_ID不匹配",
			})
			ctx.Abort()
			return
		}
		ctx.Set(consts.AppID, claims[consts.AppID])
		ctx.Set(consts.UID, claims[consts.UID])
		ctx.Set(consts.Platform, ctx.Request.Header.Get(consts.Platform))
		ctx.Next()
	}
}
